package com.ninong.ker.common.tools;

import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class CommonUtil {

	public static boolean isZeroLengthTrimString(String value) {
		return value == null || value.trim().length() == 0;
	}

	public static boolean isNotZeroLengthTrimString(String value) {
		return !(isZeroLengthTrimString(value));
	}

	public static String getParamValue(HttpServletRequest request, String name) {
		String value = request.getParameter(name);
		if (isZeroLengthTrimString(value)) {
			return "";
		}
		return value;
	}

	public static Date getAddDate(String yyyy_MM_DD, int days) {
		if (yyyy_MM_DD == null) {
			return new Date();
		}
		String[] calendar = yyyy_MM_DD.split("-");
		GregorianCalendar gc = new GregorianCalendar();
		gc.set(Integer.parseInt(calendar[0]), Integer.parseInt(calendar[1]) - 1, Integer.parseInt(calendar[2]), 0, 0,
				0);
		gc.add(5, days);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return java.sql.Date.valueOf(sdf.format(gc.getTime()));
	}

	public static String getIdSQLParam(Long[] ids) {
		if (ids == null || ids.length == 0) {
			return null;
		}
		StringBuffer param = new StringBuffer("");
		for (int i = 0; i < ids.length; i++) {
			if (i > 0) {
				param.append(",");
			}
			param.append("?");
		}
		return param.toString();
	}

	public static SimpleDateFormat getSampleDateFormat(String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf;
	}

	/**
	 * 密码加密的方法
	 * 
	 * @param password
	 * @return
	 */
	public static String encrypt(String password) {
		String enStr = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update("microinsight".getBytes());
			byte[] pswKey = md.digest();
			DESKeySpec desKeySpec = new DESKeySpec(pswKey);
			SecretKeyFactory desKeyFac = SecretKeyFactory.getInstance("DES");
			SecretKey desKey = desKeyFac.generateSecret(desKeySpec);
			Cipher encryptCipher = Cipher.getInstance("DES");
			encryptCipher.init(Cipher.ENCRYPT_MODE, desKey);
			byte[] enPassword = encryptCipher.doFinal(password.getBytes("UTF8"));
			enStr = new BASE64Encoder().encode(enPassword);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return enStr;
	}

	/**
	 * 32位md5加密方法
	 * 
	 * @param sourceStr
	 * @return
	 */
	public static String MD5_32(String sourceStr) {
		String result = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(sourceStr.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0) {
					i += 256;
				}
				if (i < 16) {
					buf.append("0");
				}
				buf.append(Integer.toHexString(i));
			}
			result = buf.toString();
			System.out.println("MD5(" + sourceStr + ",32) = " + result);
		} catch (NoSuchAlgorithmException e) {
			System.out.println(e);
		}
		return result;
	}

	public static String getNextUpEn(String en) {
		char lastE = 'a';
		char st = en.toCharArray()[0];
		if (Character.isUpperCase(st)) {
			if (en.equals("Z")) {
				return "A";
			}
			if (en == null || en.equals("")) {
				return "A";
			}
			lastE = 'Z';
		} else {
			if (en.equals("z")) {
				return "a";
			}
			if (en == null || en.equals("")) {
				return "a";
			}
			lastE = 'z';
		}
		int lastEnglish = (int) lastE;
		char[] c = en.toCharArray();
		if (c.length > 1) {
			return null;
		} else {
			int now = (int) c[0];
			if (now >= lastEnglish) {
				return null;
			}
			char uppercase = (char) (now + 1);
			return String.valueOf(uppercase);
		}
	}

	/**
	 * 获取日期所在月份的第一天
	 * @param date
	 * @return
	 */
	public static Date getFirstDayDateOfMonth(final Date date) {
		final Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		final int last = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
		cal.set(Calendar.DAY_OF_MONTH, last);
		return cal.getTime();

	}

	/**
	 * 获取日期所在月份的最后一天
	 * @param date
	 * @return
	 */
	public static Date getLastDayOfMonth(final Date date) {
		final Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		final int last = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		cal.set(Calendar.DAY_OF_MONTH, last);
		return cal.getTime();

	}
	
	 /**
     * 获取当前日期的前12个月
     * @return
     */
    public static String[] getPastMonthDate(int qty) {
        String[] lastMonths = new String[qty];
        Calendar cal = Calendar.getInstance();
        //如果当前日期大于二月份的天数28天或者29天会导致计算月份错误，会多出一个三月份，故设置一个靠前日期解决此问题
        cal.set(Calendar.DAY_OF_MONTH, 1);
        for (int i = 0; i < qty; i++) {
        		lastMonths[qty-1 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1)+"-"+"01";
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月
        }
        return lastMonths;
    }
    
    /**
     * 获取当前日期的前12个月
     * @return
     */
    public static String[] getPastMonth(int qty) {
        String[] lastMonths = new String[qty];
        Calendar cal = Calendar.getInstance();
        //如果当前日期大于二月份的天数28天或者29天会导致计算月份错误，会多出一个三月份，故设置一个靠前日期解决此问题
        cal.set(Calendar.DAY_OF_MONTH, 1);
        for (int i = 0; i < qty; i++) {
        		lastMonths[qty-1 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月
        }
        return lastMonths;
    }
}
